package org.haifi.game;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.List;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import javax.tools.JavaFileManager.Location;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//@Component
//@Lazy(false)
public class TestScriptUtil {
	// @PostConstruct
	public void init() {
		// 动态生成class,替换原有类行为
		try {
			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			StringBuilder builder = new StringBuilder();
			builder.append("package org.haifi.game;");
			builder.append("import org.haifi.game.AAA;");
			builder
					.append("import org.haifi.game.pb.TestAction.TestActionParam;");
			builder.append("public class TestScript2 implements AAA{");
			builder.append("	public   void print() {");
			builder.append("		System.out.println(\"hello222 test\");");
			builder.append("try {");
			builder.append("TestActionParam.newBuilder().build();");
			builder.append(" } catch (Exception e) {");
			builder.append("System.out.println(e);");
			builder.append("}");
			builder.append("	}");
			builder.append("}");
			StandardJavaFileManager fm = compiler.getStandardFileManager(null,
					null, null);
			Location location = StandardLocation.CLASS_OUTPUT;
			File file = new File("ttt");
			if (!file.exists()) {
				file.mkdirs();
			}
			File[] outputs = new File[] { file };
			try {
				fm.setLocation(location, Arrays.asList(outputs));
			} catch (IOException e) {
				e.printStackTrace();
			}

			JavaFileObject fileObject = new JavaSourceFromString("TestScript2",
					builder.toString());
			List<JavaFileObject> jfos = Arrays.asList(fileObject);
			// jfos.add(fileObject);
			boolean b = compiler.getTask(null, fm, null, null, null, jfos)
					.call();
			System.out.println("b:" + b);
			ClassLoader classLoader = ClassLoader.getSystemClassLoader();
			log.info(classLoader.getClass());

			ClassLoader classLoader2 = Thread.currentThread()
					.getContextClassLoader();

			log.info(classLoader2.getClass());

			URL url = file.toURI().toURL();
			log.info(url.getFile());
			log.info(url);
			// URL url2 = new URL("classpath:");
			URL[] urls = new URL[] { url };
			URLClassLoader classLoader3 = new URLClassLoader(urls);

			Object object = classLoader3
					.loadClass("org.haifi.game.TestScript2").newInstance();
			log.info(object.getClass());
			AAA aaa = (AAA) object;
			aaa.print();

			// TODO:成功一半了，下一步是让classloader能查找到AAA.java,估计设置多个url就可以解决。
			// 然后需要查找到AAA所在的url
		} catch (Exception e) {
			log.error("ERROR", e);
		}
	}

	private static final Log log = LogFactory.getLog(TestScriptUtil.class);
}

class JavaSourceFromString extends SimpleJavaFileObject {
	final String code;

	JavaSourceFromString(String name, String code) {
		super(URI.create("string:///" + name + Kind.SOURCE.extension),
				Kind.SOURCE);
		this.code = code;
	}

	@Override
	public CharSequence getCharContent(boolean ignoreEncodingErrors) {
		return code;
	}
}
